/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.engine.cmd.api;

import cn.easyplatform.dos.EnvDo;
import cn.easyplatform.dos.UserDo;
import cn.easyplatform.entities.BaseEntity;
import cn.easyplatform.entities.beans.api.ApiBean;
import cn.easyplatform.i18n.I18N;
import cn.easyplatform.interceptor.AbstractCommand;
import cn.easyplatform.interceptor.CommandContext;
import cn.easyplatform.lang.Strings;
import cn.easyplatform.log.LogManager;
import cn.easyplatform.messages.request.ApiRequestMessage;
import cn.easyplatform.messages.request.SimpleRequestMessage;
import cn.easyplatform.messages.response.SimpleResponseMessage;
import cn.easyplatform.messages.vos.ApiCallVo;
import cn.easyplatform.messages.vos.ApiVo;
import cn.easyplatform.services.IProjectService;
import cn.easyplatform.type.DeviceType;
import cn.easyplatform.type.EntityType;
import cn.easyplatform.type.IResponseMessage;
import cn.easyplatform.type.UserType;
import cn.easyplatform.util.MessageUtils;
import cn.easyplatform.util.RuntimeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author: <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @Description:
 * @Since: 2.0.0 <br/>
 * @Date: Created in 2019/10/29 11:02
 * @Modified By:
 */
public class CallCmd extends AbstractCommand<SimpleRequestMessage> {

    private final static Logger log = LoggerFactory.getLogger(CallCmd.class);

    public CallCmd(SimpleRequestMessage req) {
        super(req);
    }

    @Override
    public IResponseMessage<?> execute(CommandContext cc) {
        ApiCallVo av = (ApiCallVo) req.getBody();
        if (log.isInfoEnabled())
            log.info("api call:{} {} {}", av.getAppId(), av.getApiId(), av.getData());
        //boolean setEnv = cc.getEnv() == null;
        //if (setEnv) {
        IProjectService projectservice = null;
        for (IProjectService ps : cc.getEngineConfiguration()
                .getProjectServices()) {
            if (ps.getId().equals(av.getAppId())) {
                projectservice = ps;
                break;
            }
        }
        if (projectservice == null)
            return MessageUtils.projectNotFound();
        EnvDo env = new EnvDo(projectservice.getId(), DeviceType.API,
                projectservice.getLanguages().get(0), null, null);
        cc.setupEnv(env);
        //}
        try {
            BaseEntity e = cc.getEntity(av.getApiId());
            if (!(e instanceof ApiBean))
                return MessageUtils.entityNotFound(EntityType.API.getName(),
                        av.getApiId());
            ApiBean ab = (ApiBean) e;
            if (!ab.isAnonymous())
                return new SimpleResponseMessage("e200", I18N.getLabel("api.access.error"));
            if (Strings.isBlank(ab.getRefId()))
                return MessageUtils.entityNotFound(EntityType.API.getName(),
                        av.getApiId());
            //if (setEnv) {
            //设置匿名用户
            UserDo guest = RuntimeUtils.createGustUser("anonymous", UserType.TYPE_ANONYMOUS, cc.getEnv(), cc.getProjectService());
            guest.setIp(av.getIp());
            cc.setUser(guest);
            // }
            ApiVo apiVo = new ApiVo();
            apiVo.setGetTotal(av.getGetTotal());
            apiVo.setData(av.getData());
            apiVo.setId(av.getApiId());
            apiVo.setPageSize(av.getPageSize());
            apiVo.setStartNo(av.getPageNo());
            ApiCmd cmd = new ApiCmd(new ApiRequestMessage(apiVo));
            return cmd.execute(cc);
        } finally {
            cc.logout();
            LogManager.stopUser(cc.getUser());
        }
    }

    @Override
    public String getName() {
        return "apis.call";
    }
}
